package mwa.cs.sm.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.ReaderDAO;
import mwa.cs.dao.RouteDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.WaterChargeDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Route;
import mwa.cs.model.WaterCharge;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS12002Srvl
 */
public class CS12003Srvl extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private Database db;
	private String vaAgentBrowser;
	private String vaUrlAddress;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	
	public CS12003Srvl() {
		super();
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");		
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
		String vaProcessType = "";

		try {
			vaProcessType = request.getParameter("process_type");
		} catch (Exception ex) {
		}

		if (vaProcessType.equals("insert")) {
			insert(request, response);
		} else if (vaProcessType.equals("update")) {
			edit(request, response);
		} else if (vaProcessType.equals("delete")) {
			delete(request,response);
		} else if (vaProcessType.equals("db")) {
			getDbStatus(request, response);
		} else {
			getDataTable(request, response);
		}

	}

	public void delete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");	
		this.db = new Database();
		
		String vaCustomerClass = request.getParameter("CUSTOMER_CLASS").toString();
		int vnWaterUsedStart = Integer.parseInt(request.getParameter("WATER_USED_START"));
		int vnWaterUsedEnd = Integer.parseInt(request.getParameter("WATER_USED_END"));
		
		WaterChargeDAO voWaterChargeDAO = new WaterChargeDAO(db);
		boolean vbCanDelete = false;
		try {
			db.beginTransaction();
			vbCanDelete = voWaterChargeDAO.delete(vnSiteId, vaCustomerClass, vnWaterUsedStart, vnWaterUsedEnd);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12003", JDate.getDate(), JDate.getTime(),vnUserId, "CS12003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		}
		
		db.close();
		
		if(vbCanDelete)
			response.getWriter().write("success");
		else
			response.getWriter().write("fail");
	}

	public void insert(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		int vnInputWaterTo = Integer.parseInt(request
				.getParameter("inputWaterTo"));
		int vnInputWaterEnd = Integer.parseInt(request
				.getParameter("inputWaterEnd"));
		float vnInputWaterRate = Float.parseFloat(request
				.getParameter("inputWaterRate"));
		float vnInputWaterBase = Float.parseFloat(request
				.getParameter("inputWaterBase"));
		float vnInputWaterBaseCharge = Float.parseFloat(request
				.getParameter("inputWaterBaseCharge"));

		String vaInputCustomerClassVal = request
				.getParameter("inputCustomerClassVal");

		try
		{
			this.db = new Database();
		}
		catch(Exception ex)
		{
			response.getWriter().write("connect_db_fail");
		}
		
		WaterChargeDAO voWaterChargeDAO = new WaterChargeDAO(db);
		
		boolean vbIsDuplicate = voWaterChargeDAO.isDuplicate(vnSiteId, vaInputCustomerClassVal, vnInputWaterTo, vnInputWaterEnd);
		
		if (!vbIsDuplicate) 
		{
			// Can Insert
			String vaDate = JDate.getDate();
			String vaTime = JDate.getTime();

			try {
				db.beginTransaction();
				WaterCharge voWaterCharge = new WaterCharge();

				voWaterCharge.setVnSiteId(vnSiteId);
				voWaterCharge.setVaCustomerClass(vaInputCustomerClassVal);
				voWaterCharge.setVnWaterUsedStart(vnInputWaterTo);
				voWaterCharge.setVnWaterUsedEnd(vnInputWaterEnd);
				voWaterCharge.setVnWaterRate(vnInputWaterRate);
				voWaterCharge.setVnWaterBaseConsumption(vnInputWaterBase);
				voWaterCharge.setVnWaterBaseCharge(vnInputWaterBaseCharge);
				voWaterCharge.setVnInsertUserId(vnUserId);
				voWaterCharge.setVaInsertDate(vaDate);
				voWaterCharge.setVaInsertTime(vaTime);
				voWaterCharge.setVnUpdateUserId(vnUserId);
				voWaterCharge.setVaUpdateDate(vaDate);
				voWaterCharge.setVaUpdateTime(vaTime);

				boolean vbResult = voWaterChargeDAO.Insert(voWaterCharge);
				db.commit();

				if (vbResult)
					response.getWriter().write("success");
				else
					response.getWriter().write("fail");
			} catch (Exception ex) {
				db.rollback();
				SMErrorLogDAO.getInstance().addLog(0, "CS12003", JDate.getDate(), JDate.getTime(),vnUserId, "CS12003Srvl", ex.getMessage(),vaUrlAddress, vaAgentBrowser);
				response.getWriter().write("fail");
			} finally{
				db.close();
			}
		} else {
			// Can not insert, Duplicate
			db.close();
			response.getWriter().write("duplicate");
		}
	}

	public void edit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		int vnInputWaterTo = Integer.parseInt(request
				.getParameter("inputWaterTo"));
		int vnInputWaterEnd = Integer.parseInt(request
				.getParameter("inputWaterEnd"));
		float vnInputWaterRate = Float.parseFloat(request
				.getParameter("inputWaterRate"));
		float vnInputWaterBase = Float.parseFloat(request
				.getParameter("inputWaterBase"));
		float vnInputWaterBaseCharge = Float.parseFloat(request
				.getParameter("inputWaterBaseCharge"));
		String vaInputCustomerClassVal = request
				.getParameter("inputCustomerClassVal");

		int vnOldCodeID = Integer.parseInt(request.getParameter("oldCodeID")); // water_start
		int vnOldCodeID2 = Integer.parseInt(request.getParameter("oldCodeID2")); // water_end
		String vaOldCustomerClass = request.getParameter("oldCustomerClass");

		this.db = new Database();
		WaterChargeDAO voWaterChargeDAO = new WaterChargeDAO(db);
		PrintWriter voOut = response.getWriter();

		// หาว่ามี record นี้ใน database ไหม
		List<Map<String, Object>> voResult = voWaterChargeDAO.findWaterToWaterEnd(vnSiteId,
				vaOldCustomerClass, vnOldCodeID, vnOldCodeID2);
		if (voResult == null || voResult.size() == 0) {
			// record นี้ไม่มีใน database
			db.close();
			voOut.print("fail");
			return;
		}

		if (!vaInputCustomerClassVal.trim().equals(vaOldCustomerClass.trim())
				|| vnInputWaterTo != vnOldCodeID || vnInputWaterEnd != vnOldCodeID2) {
			// เช็คว่า water_start, water_end, customer_class, site อันใหม่ที่จะ
			// save มีแล้วหรือยัง
			voResult = voWaterChargeDAO.findWaterToWaterEnd(vnSiteId, vaInputCustomerClassVal,
					vnInputWaterTo, vnInputWaterEnd);
			if (voResult != null && voResult.size() > 0) {
				// record นี้ไม่มีใน database
				db.close();
				voOut.print("duplicate");
				return;
			}
		}

		String vaDate = JDate.getDate();
		String vaTime = JDate.getTime();

		WaterCharge voWaterCharge = new WaterCharge(vnSiteId, vaInputCustomerClassVal,
				vnInputWaterTo, vnInputWaterEnd, vnInputWaterRate, vnInputWaterBase,
				vnInputWaterBaseCharge, vnUserId, vaDate, vaTime, vnUserId, vaDate,
				vaTime);

		boolean vbCanUpdate = false;
		try {
			db.beginTransaction();
			vbCanUpdate = voWaterChargeDAO.update(voWaterCharge, vaOldCustomerClass, vnOldCodeID, vnOldCodeID2);
			db.commit();
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS12003", JDate.getDate(), JDate.getTime(),vnUserId, "CS12003Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			e.getMessage();
		} finally{
			db.close();
		}
		
		
		
		if (vbCanUpdate)
			voOut.print("success");
		else
			voOut.print("fail");
	}

	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		JSONObject voObject = new JSONObject();
		JSONArray voRow = new JSONArray();
		JSONArray voColomn = null;

		PrintWriter voOut = response.getWriter();

		try {
			this.db = new Database();
		} catch (Exception ex) {
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			
			db.close();
			
			voOut.print(voObject.toJSONString());
			return;
		}

		// customerClass
		String voCustomerClass = request.getParameter("customerClass");

		if (voCustomerClass.length() == 0) {
			// ไม่ได้เลือก ประเภทผู้ใช้น้ำ
			voObject.put("iTotalRecords", 0);
			voObject.put("iTotalDisplayRecords", 0);
			voObject.put("aaData", voRow);
			
			db.close();
			
			voOut.print(voObject.toJSONString());
		} else {
			// เลือกประเภทผู้ใช้น้ำ
			WaterChargeDAO voWaterChargeDAO = new WaterChargeDAO(db);

			List<Map<String, Object>> voListFindAll = voWaterChargeDAO
					.findCalPrepareData_Decimal2Digits(vnSiteId, voCustomerClass);

			for (int i = 0; i < voListFindAll.size(); i++) {
				Map<String, Object> voMapItem = (Map<String, Object>) voListFindAll
						.get(i);
				voColomn = new JSONArray();
				voColomn.add(i + 1);
				voColomn.add(voMapItem.get("WATER_USED_START"));
				voColomn.add(voMapItem.get("WATER_USED_END"));
				voColomn.add(voMapItem.get("WATER_RATE"));
				voColomn.add(voMapItem.get("WATER_BASE_CONSUMPTION"));
				voColomn.add(voMapItem.get("WATER_BASE_CHARGE"));
				voRow.add(voColomn);
			}

			voObject.put("iTotalRecords", voListFindAll.size());
			voObject.put("iTotalDisplayRecords", voListFindAll.size());
			voObject.put("aaData", voRow);
			
			db.close();
			
			voOut.print(voObject.toJSONString());
		}
	}

	public void getDbStatus(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");

		PrintWriter voOut = response.getWriter();

		try {
			this.db = new Database();

			voOut.print("success");
		} catch (Exception ex) {
			
			voOut.print("connect_db_fail");
		} finally{
			db.close();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
